package com.bot.rf.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

import static com.bot.rf.util.MyLogger.LOGGER;
import static com.bot.rf.util.MyLogger.getTrace;

/**
 * @program: report-form-demo
 * @description: socket 工具类
 * @author: zyy
 * @create: 2021-02-26 16:48
 **/
public class SocketUtil implements Runnable {

    private static Socket socket;
    private static OutputStream os;

    /**
     * 数据库配置信息
     * 122.227.160.98
     * 13624
     **/
    public static String HOST = "122.227.160.98";
    /**
     * 数据库端口12
     */
    public static int PORT_NO = 13626;
    /**
     * 设备编号
     */
    public static int DEVICE_NO = 79;


    public static boolean createSocket() {
        try {
            socket = new Socket(HOST, PORT_NO);
            os = socket.getOutputStream();
        } catch (IOException e) {
            LOGGER.error(getTrace(e));
            return false;
        }
        return true;
    }


    /**
     * Description: 执行数据库查询命令str获取返回结果，命令解析见文档
     *
     * @param: 命令
     * @return: 返回结果
     * Author: wing
     * Date: 2019/12/14 14:52
     */
    public static String executeCommand(String str) {
        if (socket == null) {
            try {
                socket = new Socket(HOST, PORT_NO);
            } catch (IOException e) {
                LOGGER.error(getTrace(e));
                return "";
            }
        }
        if (socket.isClosed()) {
            createSocket();
        }
        String re = "";
        try {

            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();
            os.write(str.getBytes());

            byte[] b = new byte[10000];
            int len = -1;
            if ((len = is.read(b)) > 0) {
                re = new String(b, 0, len, StandardCharsets.UTF_8);
            }

            is.close();
            os.close();
        } catch (Exception e) {
            LOGGER.error(getTrace(e));
            createSocket();
        }
        LOGGER.info("服务端传输下来的数据："+re);
        return re;
    }

    public static void closeSocket() {
        try {
            socket.close();
        } catch (IOException e) {
            LOGGER.error(getTrace(e));
        }
    }

    @Override
    public void run() {

    }
}
